package com.baselibrary.adapter

import android.text.TextUtils
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentTransaction
import com.baselibrary.bean.TabsBean

/**
 * @author zhanglijie
 * @description:
 * @date : 2021/05/25
 */
class ViewPagerAdapter : FragmentPagerAdapter {
    var fragmentList: ArrayList<Fragment>
    var mTitles: ArrayList<TabsBean>? = null
    private var fm: FragmentManager? = null

    constructor(fm: FragmentManager?, fragmentList: ArrayList<Fragment>) : super(fm!!) {
        this.fragmentList = fragmentList
    }

    fun setList(list: List<Fragment>, titles: List<TabsBean>) {
        if (null != this.fragmentList) {
            fragmentList.clear()
            fragmentList.addAll(list)
        }
        if (null != this.mTitles) {
            mTitles!!.clear()
            mTitles!!.addAll(titles)

        }
        notifyDataSetChanged()
    }

    constructor(fm: FragmentManager?, fragmentList: List<Fragment>, mTitles: List<TabsBean>?) : super(fm!!) {
        this.fragmentList = fragmentList as ArrayList<Fragment>
        this.mTitles = mTitles as ArrayList<TabsBean>
        this.fm = fm
    }

    override fun getPageTitle(position: Int): CharSequence {
        if (position < mTitles!!.size) {
            return if (!TextUtils.isEmpty(mTitles!![position].name)) mTitles!![position].name else ""
        } else {
            return ""
        }
    }

    override fun getItem(position: Int): Fragment {
        return fragmentList[position]
    }

    override fun getCount(): Int {
        return if (null != fragmentList) {
            fragmentList.size
        } else {
            0
        }

    }

//    override fun instantiateItem(container: ViewGroup, position: Int): Any {
//        var f = super.instantiateItem(container, position) as Fragment
//        val fragmentTag = f.tag
//        if (f !== getItem(position)) {
//            //如果是新建的fragment，f 就和getItem(position)是同一个fragment，否则进入下面
//            val ft: FragmentTransaction = this.fm!!.beginTransaction()
//            //移除旧的fragment
//            ft.remove(f)
//            //换成新的fragment
//            f = getItem(position)
//            //添加新fragment时必须用前面获得的tag
//            ft.add(container.id, f, fragmentTag)
//            ft.attach(f)
//            ft.commitAllowingStateLoss()
//        }
//        return f
//    }
}